<?php

class SCup_Default extends BaseModel
{
    var $table  = 'users';	
    var $_page_rows = 20;	
	//检查用户名是否合法
	function check_username_form($username) 
	{
		$guestexp = '\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8';
		$len = strlen($username);
		if($len > 15 || $len < 3 || preg_match("/\s+|^c:\\con\\con|[%,\*\"\s\<\>\&]|$guestexp/is", $username)) 
		{
			return FALSE;
		} else 
		{
			return TRUE;
		}
	}
	
	//检查用户名是否合法
	function check_email_form($email) 
	{
		if(!preg_match("/^[-a-zA-Z0-9_\.]+\@([0-9A-Za-z][0-9A-Za-z-]+\.)+[A-Za-z]{2,5}$/i",$email))
	    {
			return FALSE;
		} else 
		{
			return TRUE;
		}
	}

    /* 修改数据 */
    function oneedit($str,$id ='',$data = '')
    {  	      
		return $this->IU_Sql_Exe(array ('data' => array("{$str}"=>"$data"),'mode' => 'UPDATE','conditions' =>"user_id = '{$id}' "));    
    }


    function show($order='',$v='',$word='',$conditions='',$words='',$condition='',$fieldtype='',$roleid='',$usertype='0')
    {   
	     empty($fieldtype)?$fieldtype = 'user_name':'';	     
	     empty($order)?$order = 'reg_time desc':'';
		 if($conditions)
		 {
		 $conditions .=' and 1 ';
		 }else
		 {
		 $conditions =' 1 ';		 
		 }		 
		 foreach($word as $key => $value)
		 {	
		     if($value)
		     {
		          $conditions .= " and {$fieldtype} like '%{$value}%' ";	  
		     }
		 }	 
	  	 if($roleid)
		 {
		    $conditions .= " and role_id='{$roleid}' ";
		 }
	  	 if($usertype)
		 {
		    $conditions .= " and user_type={$usertype} ";
		 }		 
		 
	      //分页时，一定是先调用page函数，再调用S_Sql_Exe函数
		 $info['page'] = $this->Page(array('conditions' =>"{$conditions}",'url' => 'admin/?app=user&act=index&v='.$v.'&roleid='.$roleid.'&usertype='.$usertype.'&condition='.$condition.'&word='.$words.'&fieldtype='.$fieldtype));		
		 $info['data'] = $this->S_Sql_Exe(array('fields' =>'*','conditions' =>"{$conditions}",'order' =>"{$order}",'limit' =>$info['page']['sql_limit']));
    
		 return $info;
        
    }	
    /**
     *    检查电子邮件是否唯一
     */
    function check_email_one($email)
    {

	    if(!$this->check_email_form($email))
		{
		 exit('email form error');
		}		
        $info = $this->S_Sql_Exe(array('fields' =>'user_email','conditions' =>"user_email = '{$email}'",'limit' =>'1','return' =>'one'));
		
        if (!empty($info))
        {
            exit('email_exists');

            return false;
        }

        return true;
    }

    /**
     *    检查用户名是否唯一
     */
    function check_username_one($user_name)
    {   
	    if(!$this->check_username_form($user_name))
		{
		 exit('username form error');
		}
	
        $info = $this->S_Sql_Exe(array('fields' =>'user_name','conditions' =>"user_name = '{$user_name}'",'limit' =>'1','return' =>'one'));
		
        if (!empty($info))
        {
            exit('user_exists');

            return false;
        }

        return true;
    }

    /* 获取用户信息 */
    function get_info($value , $field_name='user_name')
    {    
	    if(empty($value))
		{
		return false;
		}
		
        return $this->S_Sql_Exe(array('conditions' =>"{$field_name} = '{$value}'",'limit' =>'1','return' =>'one'));
       
    }
    /* 注册 */
    function reg($data)
    {    

	    if(!$data['username'])
		{
		
		 $notice = &get_message(array('msg'=>"用户名不能为空!",'url'=>SITE_URL.'/?app=login&act=reg','title'=>'Notice'));
		 $notice ->display();		

		}
		if(!$data['email'])
		{
		 $notice = &get_message(array('msg'=>"邮箱不能为空!",'url'=>SITE_URL.'/?app=login&act=reg','title'=>'Notice'));
		 $notice ->display();		

		}
		if(!$data['password'])
		{
		 $notice = &get_message(array('msg'=>"密码不能为空!",'url'=>SITE_URL.'/?app=login&act=reg','title'=>'Notice'));
		 $notice ->display();			
		
		}
		
		if ($data['password']!=$data['check_passwd'])
		{
		 $notice = &get_message(array('msg'=>"两次输入密码不一样!",'url'=>SITE_URL.'/?app=login&act=reg','title'=>'Notice'));
		 $notice ->display();			

		}
				
		if(strlen($data['username'])>15||strlen($data['username'])<3)
		{
		 $notice = &get_message(array('msg'=>"用户名不能小于3个字节或大于15个字节!",'url'=>SITE_URL.'/?app=login&act=reg','title'=>'Notice'));
		 $notice ->display();		
		

		}
		if (strlen($data['password'])>30 || strlen($data['password'])<5)
		{
		 $notice = &get_message(array('msg'=>"密码不能小于5个字符或大于30个字符!",'url'=>SITE_URL.'/?app=login&act=reg','title'=>'Notice'));
		 $notice ->display();			

		}
		
		if(!isset($data['roleid']))
		{
		$data['roleid'] = ROLE_P_ID;
		}
		
		$S_key=array('|',' ','',"'",'"','/','*',',','~',';','<','>','$',"\\","\r","\t","\n","`","!","?","%","^");
		foreach($S_key as $value)
		{
			if (strpos($data['username'],$value)!==false)
			{ 
		 $notice = &get_message(array('msg'=>'用户名中包含有禁止的符号“{$value}”','url'=>SITE_URL.'/?app=login&act=reg','title'=>'Notice'));
		 $notice ->display();				

			}
			if (strpos($data['password'],$value)!==false)
			{
		 $notice = &get_message(array('msg'=>'密码中包含有禁止的符号“{$value}”','url'=>SITE_URL.'/?app=login&act=reg','title'=>'Notice'));
		 $notice ->display();				
			
			}
		}
		$data['password'] = md5($data['password']);
		$last_ip = get_ip();
		$time = time();
		
        $this->check_username_one($data['username']);
        $this->check_email_one($data['email']);	        

	    $usertype = intval($data['user_type']);
	
        if(empty($usertype))
		{
		     return $this->IU_Sql_Exe(array ('data' => array('user_email'=>$data['email'],'user_name'=>$data["username"],'user_passwd'=>$data["password"],'role_id'=>$data["roleid"],'user_question'=>"",'user_answer'=>"",'user_type'=>$data['user_type'],'reg_time'=>"$time",'last_login_time'=>"$time",'last_ip'=>"$last_ip"), 'mode' => 'INSERT'));

		}
	    $table = DB_PREFIX.'usertype_'.$usertype;	
	    $db = & get_db();							
		if($db->table_exists($table))
		{	
		        $tempicon = $this->IU_Sql_Exe(array ('data' => array('user_email'=>$data['email'],'user_name'=>$data["username"],'user_passwd'=>$data["password"],'role_id'=>$data["roleid"],'user_question'=>"",'user_answer'=>"",'user_type'=>$data['user_type'],'reg_time'=>"$time",'last_login_time'=>"$time",'last_ip'=>"$last_ip"), 'mode' => 'INSERT'));
		        $userid = $db->insert_id();	
				if($tempicon&&$userid)
				{
                      $info = $this->S_Sql_Exe(array('table' =>$table,'fields' =>'user_id','conditions' =>"user_id = '{$userid}'",'limit' =>'1','return' =>'one'));
                      if($info['user_id'])
		              {
					  return 1;		   
		              }								     
		              return $this->IU_Sql_Exe(array ('table' =>$table,'data' => array('user_id'=>$userid,'user_name'=>$data["username"]), 'mode' => 'INSERT'));	
					 	
				}else
				{
				   return 0;
				}	   
		
		}else
		{
		   $notice = &get_message(array('msg'=>'用户类型不存在!','url'=>'','title'=>'Notice'));
		   $notice ->display();		  
		}
        
    }


    /**
     *    验证用户登录
     *
     *    @author    Garbin
     *    @param     $string $user_name
     *    @param     $string $password
     *    @return    int    用户ID
     */
    function login($user_name, $password)
    {
        $info = $this->S_Sql_Exe(array('fields' =>'user_id,user_name,user_email,user_passwd,role_id,user_type,due_time,user_ico,locked,config','conditions' =>"user_name = '{$user_name}'",'limit' =>'1','return' =>'one'));
        if ($info['user_passwd'] != md5($password))
        {
            $this->message('login_failed');
            return 0;
        } 
		         
        if ($info['locked'])
        {
            $this->message('be locked');

            return 0;
        }
		if($info['due_time'])
		{
           $temp = $this->duetime($info['due_time']);
		   if($temp)
		   {
		     $info['role_id'] = $temp;
		   }  		
		}  
  
		unset($info['user_passwd']);
        $GLOBALS['SCup']->SCup_user_msg['data'] = $info;		
		unset($GLOBALS['SCup']->SCup_user_msg['data']['user_id']);
		$GLOBALS['SCup']->SCup_user_msg['user_id'] = $info['user_id'];
		//$GLOBALS['SCup']->SCup_user_session->update_session();此代码不需要，因为mysession会在最后调用
         $GLOBALS['SCup']->SCup_user_checking = true;
		 
		$this->editmsg(array('user_id'=>$info['user_id'],'last_login_time'=>time())); 		 
        return $info['user_id'];
    }

	function duetime($time=0)
	{
	    $nowtime = time();
	    if($nowtime>$time)
		{		
		   return ROLE_P_ID;
		}else
		{
		   return 0;
		}
	}

	//用户退出
	function quit()
	{
		
		if($GLOBALS['SCup']->SCup_user_session->destroy_session())
		{
           return true ;
		
		}
		
		return false;
	}


    /* 修改 */
    function edit($data)
    {    

        $data['user_type'] = intval($data['user_type']);
        $temp_data = array();  

		if ($data['password']&&($data['password']!=$data['check_passwd']))
		{
						    $this->message('两次输入密码不一样');

		}
		if ($data['password']&&(strlen($data['password'])>30 || strlen($data['password'])<5))
		{
			   $this->message('密码不能小于5个字符或大于30个字符');

		}
		
		if(!isset($data['roleid']))
		{
		$data['roleid'] = ROLE_P_ID;
		}
		
	    $temp_data['role_id'] = $data['roleid'];
		
		$info = $this->get_info($data['id'] , 'user_id');
		
		if($data['email']&&$data['email']!=$info['user_email'])
		{
		
		$this->check_email_one($data['email']);	
		$temp_data['user_email'] = $data['email'];
		}
		if(!isset($data['locked']))$data['locked']=0;
		$temp_data['locked'] = $data['locked'];
          	
		
		if($data['password'])
		{
		      $S_key=array('|',' ','',"'",'"','/','*',',','~',';','<','>','$',"\\","\r","\t","\n","`","!","?","%","^");
		      foreach($S_key as $value)
		      {

			      if (strpos($data['password'],$value)!==false)
			      {
				    $this->message('密码中包含有禁止的符号“{$value}”');

			      }  
		      }
			  
		      $data['password'] = md5($data['password']);
			  
			  $temp_data['user_passwd'] = $data['password'];			  
		}
        $user_id = $data['id'];
        unset($data['username'],$data['password'],$data['check_passwd'],$data['check_passwd'],$data['email'],$data['roleid'],$data['locked'],$data['id']);
        $temp_data = array_merge($data,$temp_data);

		if($temp_data['user_type']&&($info['user_type']!=$temp_data['user_type']))
		{
	         $db = & get_db();
		     if($db->table_exists(DB_PREFIX.'usertype_'.$info['user_type']))
		     {				 			     
             $this->D_Sql_Exe(array ('table'=>DB_PREFIX.'usertype_'.$info['user_type'],'conditions' =>"user_id = '{$user_id}' "));
			 }	
	         $usertype = intval($temp_data['user_type']);			 	
	         $table = DB_PREFIX.'usertype_'.$usertype;	
				
		     if($db->table_exists($table))
		    {	
                   $tempinfo = $this->S_Sql_Exe(array('table' =>$table,'fields' =>'user_id','conditions' =>"user_id = '{$user_id}'",'limit' =>'1','return' =>'one'));
                   if(!isset($tempinfo['user_id']))
		           {
				      $username = $info['user_name'];
		              $this->IU_Sql_Exe(array ('table' =>$table,'data' => array('user_id'=>$user_id,'user_name'=>$username), 'mode' => 'INSERT'));	
		           }								     
		
		    }else
		    {
		        $notice = &get_message(array('msg'=>'用户类型不存在!','url'=>'','title'=>'Notice'));
		        $notice ->display();		  
		    }		  
		  
		     
		}
		return $this->IU_Sql_Exe(array ('data' => $temp_data, 'mode' => 'UPDATE','conditions' =>"user_id = '".$user_id."'"));

        
    }

    /* 修改 */
    function editmsg($data)
    {    
 
        $user_id = $data['user_id'];
 	

        unset($data['user_name'],$data['user_passwd'],$data['money'],$data['user_email'],$data['role_id'],$data['locked'],$data['user_id'],$data['totalpay']);

		return $this->IU_Sql_Exe(array ('data' => $data, 'mode' => 'UPDATE','conditions' =>"user_id = '".$user_id."'"));

        
    }

	//修改密码
	function inionepwd($userid=0,$pwd='')
	{   
        $pwd = md5($pwd);	
		return $this->IU_Sql_Exe(array ('data' => array('user_passwd'=>$pwd), 'mode' => 'UPDATE','conditions' =>"user_id = '".$userid."'"));
	}

	
	//修改密码
	function pwd($data)
	{   

		$data['newpass'] = md5($data['newpass']);
		$data['oldpass'] = md5($data['oldpass']);
		$user_id = $data['user_id'];
		
        $info = $this->S_Sql_Exe(array('fields' =>'user_name,user_passwd','conditions' =>"user_id = '{$user_id}'",'limit' =>'1','return' =>'one'));
		
	
		if($data['oldpass']==$info['user_passwd'])
		{		
		return $this->IU_Sql_Exe(array ('data' => array('user_passwd'=>$data['newpass']),'mode' => 'UPDATE','conditions' =>"user_name = '".$info['user_name']."'"));
		
		}	
		
		return false;		


	}
	


	//删除会员
	function delete($value , $field_name='user_id') 
	{

	    if(empty($value))
		{
		return false;
		}
        $info = $this->S_Sql_Exe(array('fields' =>'user_id,user_name,user_type','conditions' =>"{$field_name} = '{$value}'",'limit' =>'1','return' =>'one'));
		if(!isset($info['user_id']))
		{
		return false;
		}	
	    $db = & get_db();
		if($db->table_exists(DB_PREFIX.'usertype_'.$info['user_type']))
		{	
		     $user_id = $info['user_id']; 			 			     
             $this->D_Sql_Exe(array ('table'=>DB_PREFIX.'usertype_'.$info['user_type'],'conditions' =>"user_id = '{$user_id}' "));
		}					
        return $this->D_Sql_Exe(array('conditions' =>"{$field_name} = '{$value}'"));
	
	}

	//获取会员总数
	function total($conditions = '') 
	{
	    $rs = $this->S_Sql_Exe(array('fields' =>'COUNT(*) AS NUM','conditions' =>"$conditions",'return' =>'one'));
		return $rs[NUM];
	}
	


	//信息显示
	function message($msg) 
	{
         
	}
	



}



?>